<template>
  <div id="app">
    <h1 class="buyGoods">选购商品</h1>
    <div class="product-container">
      <template class="product-box" v-for="(product, index) in products" :key="index">

        <template v-if="index != 0">
          <div>
            <h3 style="color: black;">{{ product.name }}</h3>
            <p style="color: black;">价格：{{ Math.floor(product.price / 100) }}.{{ product.price % 100 }}元</p>
            <p style="color: black;">token额度：{{ product.token }}</p>

            <button @click="open(product)">确认套餐</button>
          </div>

        </template>
      </template>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { pay } from '@/api/pay'
import { getAllTokenPackage } from '@/api/tokenPackage'
import { ElMessageBox } from 'element-plus'
import { useTokenStore } from '@/stores/user'
import { ref, reactive, onMounted } from 'vue'


onMounted(async () => {
  const result = await getAllTokenPackage();
  if (result.data.length !== 0)
    products.splice(1, products.length, ...result.data);
  else
    products.splice(1, products.length);
})


const open = async (product) => {
  try{
    await ElMessageBox.confirm("确认购买套餐？", "购买确认", {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    })

    try {
        const result = await pay(product.id);
        console.log("支付宝返回的表单" + result.data.formHtml);
        console.log("支付宝返回的表单JSON" + JSON.stringify(result.data));


        const newWindow = window.open('', '_blank');
        newWindow.document.write(result.data.formHtml);
        newWindow.document.close(); // 关闭 document 的输出流 


      } catch (error) {
        console.log("支付error:" + error);
      }


  }catch(error){
    console.log("不购买套餐" + error);
  }
  

}


const products = reactive([{
  id: -1,
  name: "",
  price: 0,
  token: 0,
}]);


</script>

<style scoped>

.app {
  text-align: center;
}


.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

.confirm-button {
  background-color: dodgerblue;
  color: white;
  width: 300px;
  height: 47px;
  border: 0;
  font-size: 16px;
  border-radius: 30px;
}

.product-container {
  display: flex;
  justify-content: space-around;
  padding: 0 10px;
}

.product-box {
  margin: 0 5px;
}

.img {
  width: 100px;
  height: 100px;
}

.buyGoods {
  margin: 200 auto;
  color: black;
  text-align: center;
}
</style>
